//
//  TwitterManagement.m
//  YaTc
//
//  Created by Roberto on 23/02/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TwitterManagement.h"
#import "TwitterPost.h"


@implementation TwitterManagement

@synthesize user, password;


- (id) initWithUser:(NSString *)theUser password:(NSString *)thePassword
{
	if ( ![super init] )
		return nil;
	
	user = theUser;
	password = thePassword;
  
  [user retain];
  [password retain];
	
	return self;
	
}

- (NSArray *) getFriendsTimeLine
{
	NSMutableArray * twitterStatuses;
	
	twitterStatuses = [[NSMutableArray alloc] init];
	/* Codigo que hace la consulta de verdad  */
	NSURL * url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://%@:%@@twitter.com/statuses/friends_timeline.xml", user, password]];
	NSURLRequest *request = [NSURLRequest requestWithURL:url 
	cachePolicy:NSURLRequestReturnCacheDataElseLoad 
	timeoutInterval:30];
	NSData *data;
	NSURLResponse *response;
	NSError *error;
	
	data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	
	if ( !data )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	 
	NSXMLDocument *doc;
	doc = [[NSXMLDocument alloc] initWithData:data options:0 error:&error];
	 
	/* ------------------------ */
	/* Codigo que pilla el xml desde un fichero  */
	/*NSError *error;
	NSXMLDocument *doc;
	doc = [[NSXMLDocument alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:@"/Users/user/Downloads/friendstimeline.xml"]
											   options:0 error:&error];*/
	/* --------------------- */
	if ( !doc )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	
	NSArray *statuses = [doc nodesForXPath:@"/statuses/status" error:&error];
	if ( !statuses )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	NSDateFormatter *dateFormatter =[[[NSDateFormatter alloc] init] autorelease];	
	[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
	[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
	[dateFormatter setTimeZone:nil];
	for ( int i = 0; i < [statuses count]; i++ )
	{
		TwitterPost *tp = [[TwitterPost alloc] init];
		NSXMLNode *status = [statuses objectAtIndex:i];
		NSString *stringData = [[[status nodesForXPath:@"./text" error:&error] objectAtIndex:0] stringValue]; 
		[tp setMessage: stringData];
		stringData = [[[status nodesForXPath:@"./id" error:&error] objectAtIndex:0] stringValue];
		[tp setPostId:stringData];
		stringData = [[[status nodesForXPath:@"./created_at" error:&error] objectAtIndex:0] stringValue];
		[tp setMessageDate:[dateFormatter dateFromString:stringData]];
		//[tp setMessage: @"wwwwwww wwwwwww wwwwww wwwwwwwwwwww wwwwwww wwwwwwww wwwwww wwwww wwwwwwwwwww wwwwwww wwwwww wwwwwww www wwwwwww www www www wwwwww wwww www"];
		stringData = [[[status nodesForXPath:@"./user/profile_image_url" error:&error] objectAtIndex:0] stringValue]; 
		[tp setImageLocation:[[NSURL alloc] initWithString:stringData]];
		stringData = [[[status nodesForXPath:@"./user/name" error:&error] objectAtIndex:0] stringValue];
		[tp setUser: stringData];
		stringData = [[[status nodesForXPath:@"./user/screen_name" error:&error] objectAtIndex:0] stringValue];
		[tp setUserId: stringData];
		stringData = [[[status nodesForXPath:@"./user/location" error:&error] objectAtIndex:0] stringValue]; 
		[tp setUserLocation:stringData];
		[tp setIsDirectMessage:NO];
		
		[twitterStatuses addObject:tp];
		
	}
	
	return twitterStatuses;
	
}

- (NSArray *) getDirectMessages
{
	NSMutableArray * directMessages;
	
	directMessages = [[NSMutableArray alloc] init];
	/* Codigo que hace la peticion de verdad */
	NSURL * url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://%@:%@@twitter.com/direct_messages.xml", user, password]];
	NSURLRequest *request = [NSURLRequest requestWithURL:url 
											 cachePolicy:NSURLRequestReturnCacheDataElseLoad 
										 timeoutInterval:30];
	NSData *data;
	NSURLResponse *response;
	NSError *error;
	
	data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	
	if ( !data )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	
	NSXMLDocument *doc;
	doc = [[NSXMLDocument alloc] initWithData:data options:0 error:&error];
	/* ------------------------ */
	/* Codigo que pilla el xml desde un fichero  */
	/*NSError *error;
	NSXMLDocument *doc;
	doc = [[NSXMLDocument alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:@"/Users/user/Downloads/direct_messages.xml"]
											   options:0 error:&error];*/
	/* --------------------- */
	
	
	if ( !doc )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	
	NSArray *statuses = [doc nodesForXPath:@"/direct-messages/direct_message" error:&error];
	if ( !statuses )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return nil;
	}
	
	NSDateFormatter *dateFormatter =[[[NSDateFormatter alloc] init] autorelease];	
	[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
	[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
	[dateFormatter setTimeZone:nil];
	for ( int i = 0; i < [statuses count]; i++ )
	{
		TwitterPost *tp = [[TwitterPost alloc] init];
		NSXMLNode *status = [statuses objectAtIndex:i];
		NSString *stringData = [[[status nodesForXPath:@"./text" error:&error] objectAtIndex:0] stringValue]; 
		[tp setMessage: stringData];
		stringData = [[[status nodesForXPath:@"./id" error:&error] objectAtIndex:0] stringValue];
		[tp setPostId:stringData];
		stringData = [[[status nodesForXPath:@"./created_at" error:&error] objectAtIndex:0] stringValue];
		[tp setMessageDate:[dateFormatter dateFromString:stringData]];
		stringData = [[[status nodesForXPath:@"./sender/profile_image_url" error:&error] objectAtIndex:0] stringValue]; 
		[tp setImageLocation:[[NSURL alloc] initWithString:stringData]];
		stringData = [[[status nodesForXPath:@"./sender/name" error:&error] objectAtIndex:0] stringValue];
		[tp setUser: stringData];
		stringData = [[[status nodesForXPath:@"./sender/screen_name" error:&error] objectAtIndex:0] stringValue];
		[tp setUserId: stringData];
		stringData = [[[status nodesForXPath:@"./sender/location" error:&error] objectAtIndex:0] stringValue]; 
		[tp setUserLocation:stringData];
		[tp setIsDirectMessage:YES];
		
		[directMessages addObject:tp];
		
	}
	
	return directMessages;
	
}

- (void) postNewTweet: (NSString *) message
{
	NSLog(@"Posting Tweet %@", message);
	NSURL* url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://%@:%@@twitter.com/statuses/update.xml", user, password]];
	NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:[[NSString stringWithFormat:@"status=%@", [message stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]
									dataUsingEncoding:NSASCIIStringEncoding]];
	NSURLResponse * response;
	NSError * error;
	NSData * data;
	
	data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	if ( !data )
	{
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
		return;
	}
	
	

}

- (BOOL) verifyCredentials
{
	NSLog(@"Verifiying user credentials...");
	NSURL * url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://%@:%@@twitter.com/account/verify_credentials.xml", user, password]];
	NSURLRequest *request = [NSURLRequest requestWithURL:url 
											 cachePolicy:NSURLRequestReturnCacheDataElseLoad 
										 timeoutInterval:30];
	NSData *data;
	NSURLResponse *response;
	NSError *error;
	
	data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
	if ( [httpResponse statusCode] != 200 )
	{
		NSLog(@"Login Failed");
		return NO;
	}
	NSLog(@"Login OK");
	return YES;
	
}

- (void) dealloc
{
	[user release];
	[password release];
	[super dealloc];
}


@end
